import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { ThrottlerException } from '@nestjs/throttler';
import { Request, Response } from 'express';

// 拓展HttpException类型 兼容参数校验包抛出的错误格式
export class ValidationException extends HttpException {
  public validationResponse: { message: string[] };

  constructor(message: string[], status?: number) {
    super(message, status || HttpStatus.BAD_REQUEST);
    this.validationResponse = { message };
  }

  getResponse(): { message: string[] } {
    return this.validationResponse;
  }
}

type ExceptionResponseType = { message: string[] } | { message?: string };

@Catch(HttpException, ValidationException)
export class ExceptionInterceptor implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost): any {
    const context = host.switchToHttp();
    const request = context.getRequest<Request>();
    const response = context.getResponse<Response>();
    const status = exception.getStatus();

    // 类型判断
    let exceptionResponse: ExceptionResponseType;
    if (exception instanceof ValidationException) {
      exceptionResponse = exception.getResponse();
    } else {
      exceptionResponse = exception.getResponse() as ExceptionResponseType;
    }

    if (exception instanceof ThrottlerException) {
      exception.message = '请求过于频繁，请稍后再试。'
    }

    response.status(status).json({
      success: false,
      time: new Date(),
      status,
      path: request.url,
      data: Array.isArray(exceptionResponse?.message) ? exceptionResponse.message : [exception.message],
    });
  }
}
